package com.bsoft.gol.hcb.service.docteam.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.bsoft.gol.hcb.service.docteam.bean.qo.AddDocTeamFusAuthorityReq;
import com.bsoft.gol.hcb.service.docteam.bean.qo.AddDocTeamMemberReq;
import com.bsoft.gol.hcb.service.docteam.bean.qo.AddDocTeamReq;
import com.bsoft.gol.hcb.service.docteam.bean.qo.AddTeamChronicDiseaseListReq;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import ctd.controller.exception.ControllerException;
import ctd.net.rpc.Client;
import ctd.spring.boot.annotation.SsdevReference;
import ctd.spring.boot.annotation.SsdevService;
import ctd.util.JSONUtils;
import ctd.util.annotation.RpcService;
import hcn.bean.specialist.qo.*;
import hcn.bean.specialist.vo.QueryDocTeamDetailResp;
import hcn.bean.specialist.vo.QueryDocTeamListResp;
import hcn.bean.specialist.vo.QuerySurveyRuleQuestionListResponse;
import hcn.bean.specialist.vo.QuerySurveyRuleQuestionListVO;
import hcn.docteam.DocTeamEntity;
import hcn.docteam.DocTeamMemberEntity;
import hcn.enums.ItemTypeEnum;
import hcn.feedback.DocTeamFeedbackType;
import hcn.specialist.*;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import com.bsoft.gol.hcb.service.docteam.dao.DocTeamDAO;
import com.bsoft.gol.hcb.service.docteam.dao.DocTeamMemberDAO;
import com.bsoft.gol.hcb.service.docteam.service.ITeamManageService;
import com.bsoft.gol.hcb.service.feedback.dao.DocTeamFeedbackTypeDAO;
import pcn.bean.docTeam.QueryAllDocTeamReq;
import pcn.service.web.BaseDeviceService;
import service.rpc.*;
import com.bsoft.gol.hcb.utils.CommonUtils;
import org.atag.util.common.RedisUtil;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author:FangZhiyi
 * @Description
 * @Data Created in 2020/7/14 15:36
 * @Moddified By:
 */
@SsdevService("teamManage")
public class TeamManageServiceImpl implements ITeamManageService {
    private static final Logger logger = LoggerFactory.getLogger(TeamManageServiceImpl.class);

    @Autowired
    DocTeamDAO docTeamDAO;
    @Autowired
    IDocTeamDiseaseRpcService docTeamDiseaseRpcService;
    @Autowired
    DocTeamMemberDAO docTeamMemberDAO;
    @Autowired
    IDiseaseSpeciesRpcService diseaseSpeciesRpcService;
    @Autowired
    IDocTeamSurveyQuestionnaireRpcService docTeamSurveyQuestionnaireRpcService;
    @Autowired
    DocTeamFeedbackTypeDAO docTeamFeedbackTypeDAO;
    @Autowired
    IDocTeamFusAuthorityService docTeamFusAuthorityService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private DoctorInfoServiceIntf docIdentityService;
    @Autowired
    IPatientSatisfactionSurveyService patientSatisfactionSurveyService;
    @Autowired
    IFusTeamChronicGroupRecordService fusTeamChronicGroupRecordService;
    @Autowired
    FollowUpRouteDetailTeamService followUpRouteDetailTeamService;

    @Override
    @RpcService
    public PageInfo queryDocTeamList(QueryDocTeamListReq docTeamListReq) {
        List<QueryDocTeamListResp> docTeamList = new ArrayList<>();
        PageInfo pageInfo = new PageInfo(docTeamList);
        Long count = docTeamDAO.queryDocTeamListCount(docTeamListReq);
        if (count > 0) {
            docTeamList = docTeamDAO.queryDocTeamList(docTeamListReq);
            if (!CollectionUtils.isEmpty(docTeamList)) {
                docTeamList.forEach(e->{e.setCount(e.getCounts());});
                pageInfo.setPageNum(docTeamListReq.getPageNo());
                pageInfo.setPageSize(docTeamListReq.getPageSize());
                pageInfo.setTotal(count);
                pageInfo.setList(docTeamList);
            }
        }
        return pageInfo;
    }

    @Override
    @RpcService
    public List<QueryDocTeamListResp> queryDocTeamByDocidList(QueryDocTeamListReq docTeamListReq) throws ControllerException {
        List<QueryDocTeamListResp> docTeamList = docTeamDAO.queryDocTeamByDocidList(docTeamListReq);
        if(CommonUtils.isNotEmpty(docTeamList)){
            for (QueryDocTeamListResp queryDocTeamListResp : docTeamList) {
                docTeamListReq.setMedicalTeamId(queryDocTeamListResp.getMedicalTeamId());
                BigInteger personIdCount = fusTeamChronicGroupRecordService.getPersonIdCount(docTeamListReq);
                if(null != personIdCount){
                    queryDocTeamListResp.setCount(personIdCount.longValue());
                }
            }
        }
        return docTeamList;
    }

    @Override
    @RpcService
    public QueryDocTeamDetailResp queryDocTeamDetail(QueryDocTeamListReq docTeamListReq) throws ControllerException {
        QueryDocTeamDetailResp docTeamDetailResp = new QueryDocTeamDetailResp();
        DocTeamEntity docTeamEntity = docTeamDAO.get(docTeamListReq.getMedicalTeamId());
        BeanUtils.copyProperties(docTeamEntity, docTeamDetailResp);

        if ("1".equals(docTeamEntity.getTeamType())) {
            List<DocTeamDiseaseEntity> diseaseList = docTeamDiseaseRpcService.queryDocTeamDiseaseList(docTeamListReq.getMedicalTeamId());//团队慢病集合
            if (CollectionUtils.isNotEmpty(diseaseList)) {
                docTeamDetailResp.setTeamChronicDiseaseList(diseaseList);
            }
        } else if ("3".equals(docTeamEntity.getTeamType())) {
            List<DocTeamFusAuthority> tempDocTeamFus =
                    docTeamFusAuthorityService.queryTeamFusList(docTeamListReq.getMedicalTeamId());
            if (CollectionUtils.isNotEmpty(tempDocTeamFus)) {
                docTeamDetailResp.setTeamFusAuthorityList(tempDocTeamFus);
            }
        } else if ("2".equals(docTeamEntity.getTeamType())) {
            List<DocTeamSurveyQuestionnaireEntity> surveyQuestionnaireEntityList = docTeamSurveyQuestionnaireRpcService.queryDocTeamSurveyQuestionnaireList(docTeamListReq.getMedicalTeamId());//团队慢病集合
            if (CollectionUtils.isNotEmpty(surveyQuestionnaireEntityList)) {
                docTeamDetailResp.setTeamSurveyQuestionnaireList(surveyQuestionnaireEntityList);
            }
            List<DocTeamFeedbackType> feedbackTypeEntityList = docTeamFeedbackTypeDAO.queryDocTeamFeedbackTypeList(docTeamListReq.getMedicalTeamId());//团队慢病集合
            if (CollectionUtils.isNotEmpty(feedbackTypeEntityList)) {
                docTeamDetailResp.setDocTeamFeedbackTypeList(feedbackTypeEntityList);
            }
        }
        return docTeamDetailResp;
    }

    @Override
    @RpcService
    public QueryDocTeamDetailResp queryDocTeamMemberDetail(QueryDocTeamListReq docTeamListReq) throws ControllerException {
        QueryDocTeamDetailResp docTeamDetailResp = new QueryDocTeamDetailResp();
        DocTeamEntity docTeamEntity = docTeamDAO.get(docTeamListReq.getMedicalTeamId());
        BeanUtils.copyProperties(docTeamEntity, docTeamDetailResp);
        //根据doctorId查询医生编码,先声明一个doctorCode
        String doctorCode = "";
        List<DocTeamMemberEntity> memberList = new ArrayList<DocTeamMemberEntity>();
        List<DocTeamMemberEntity> teamMemberList = docTeamMemberDAO.queryDocTeamMemberList(docTeamListReq.getMedicalTeamId());//团队成员集合
        //遍历teamMemberList拿到doctorId
        for (DocTeamMemberEntity docTeamMemberEntity : teamMemberList) {
            //用拿到的docId(不是医生工号)------通过RPC方法查询医生编码
            String doctorUserId = docIdentityService.getDoctorUserId(docTeamMemberEntity.getDocId());
            //用doctorUserId拿到personInfo，根据personInfo中的字典值cd拿到医生编码
            try {
                Map<String, Object> personInfo = (Map<String, Object>) Client.rpcInvoke("bbp.person","getByUserId",doctorUserId);
                if (CommonUtils.isNotEmpty(personInfo)) {
                    doctorCode = (String) personInfo.get("cd");
                    docTeamMemberEntity.setDoctorCode(doctorCode);
                }
                memberList.add(docTeamMemberEntity);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (CollectionUtils.isNotEmpty(memberList)) {
            docTeamDetailResp.setMedicalTeamMemberList(memberList);

        }
        return docTeamDetailResp;
    }

    /**
     * @Author:FangZhiyi
     * @Description 新增（修改）医疗团队
     * @Params [addDocTeamReq]
     * @Return org.atag.core.base.BaseResponse
     * @Data Created in 2020/7/16 15:31
     * @Moddified By:
     */
    @Override
    @RpcService
    public DocTeamEntity addDocTeam(AddDocTeamReq addDocTeamReq) throws ControllerException {
        DocTeamEntity docTeamEntity = new DocTeamEntity();
        //根据titleId去重
        List<DocTeamSurveyQuestionnaireEntity> teamSurveyQuestionnaireList = addDocTeamReq.getTeamSurveyQuestionnaireList();
        if(CommonUtils.isNotEmpty(teamSurveyQuestionnaireList)){
            List<DocTeamSurveyQuestionnaireEntity> unique = teamSurveyQuestionnaireList.stream().collect(
                    Collectors.collectingAndThen(
                            Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(DocTeamSurveyQuestionnaireEntity::getTitleId))), ArrayList::new));
            addDocTeamReq.setTeamSurveyQuestionnaireList(unique);
        }

        if (addDocTeamReq.getMedicalTeamId() == null) {//新增
            BeanUtils.copyProperties(addDocTeamReq, docTeamEntity);
            docTeamEntity.setEnableFlag((byte) 1);//正常状态
            docTeamEntity.setGmtCreate(new Date());
            docTeamDAO.save(docTeamEntity);
            //专科随访团队
            if ("1".equals(addDocTeamReq.getTeamType())) {
                List<DocTeamDiseaseEntity> docTeamDiseaseEntityList = addDocTeamReq.getTeamChronicDiseaseList();
                if (CollectionUtils.isNotEmpty(docTeamDiseaseEntityList)) {
                    for (DocTeamDiseaseEntity teamDiseaseEntity : docTeamDiseaseEntityList) {
                        //选中的科室代码和上级科室代码相同，说明选中的是一级科室，保存的时候上级科室代码设为空
                        if (CommonUtils.isNotEmpty(teamDiseaseEntity.getDepartmentId()) && CommonUtils.isNotEmpty(teamDiseaseEntity.getSuperiorDepartmentId())) {
                            if (teamDiseaseEntity.getDepartmentId().equals(teamDiseaseEntity.getSuperiorDepartmentId())) {
                                teamDiseaseEntity.setSuperiorDepartmentId(null);
                                teamDiseaseEntity.setSuperiorDepartmentName(null);
                            }
                        }
                        teamDiseaseEntity.setMedicalTeamId(docTeamEntity.getMedicalTeamId());
                        teamDiseaseEntity.setGmtCreate(new Date());
                        docTeamDiseaseRpcService.save(teamDiseaseEntity);
                    }
                }
                //院后随访团队
            } else if ("4".equals(addDocTeamReq.getTeamType()) || "3".equals(addDocTeamReq.getTeamType())) {
                List<DocTeamFusAuthority> docTeamFusAuthorityList = addDocTeamReq.getTeamFusAuthorityList();
                if (CollectionUtils.isNotEmpty(docTeamFusAuthorityList)) {
                    for (DocTeamFusAuthority teamFus : docTeamFusAuthorityList) {
                        //选中的科室代码和上级科室代码相同，说明选中的是一级科室，保存的时候上级科室代码设为空
                        if (CommonUtils.isNotEmpty(teamFus.getDepartmentId()) && CommonUtils.isNotEmpty(teamFus.getSuperiorDepartmentId())) {
                            if (teamFus.getDepartmentId().equals(teamFus.getSuperiorDepartmentId())) {
                                teamFus.setSuperiorDepartmentId(null);
                                teamFus.setSuperiorDepartmentName(null);
                            }
                        }
                        teamFus.setMedicalTeamId(docTeamEntity.getMedicalTeamId());
                        teamFus.setMedicalTeamName(docTeamEntity.getMedicalTeamName());
                        docTeamFusAuthorityService.save(teamFus);
                    }
                }
            }
            //意见反馈团队
            else if ("2".equals(addDocTeamReq.getTeamType())) {
                List<DocTeamSurveyQuestionnaireEntity> docTeamSurveyQuestionnaireEntityList = addDocTeamReq.getTeamSurveyQuestionnaireList();
                if (CollectionUtils.isNotEmpty(docTeamSurveyQuestionnaireEntityList)) {
                    for (DocTeamSurveyQuestionnaireEntity docTeamSurveyQuestionnaireEntity : docTeamSurveyQuestionnaireEntityList) {
                        docTeamSurveyQuestionnaireEntity.setMedicalTeamId(docTeamEntity.getMedicalTeamId());
                        docTeamSurveyQuestionnaireEntity.setMedicalTeamName(docTeamEntity.getMedicalTeamName());
                        docTeamSurveyQuestionnaireRpcService.save(docTeamSurveyQuestionnaireEntity);
                    }
                }
                List<DocTeamFeedbackType> docTeamFeedbackTypeEntityList = addDocTeamReq.getDocTeamFeedbackTypeList();
                if (CollectionUtils.isNotEmpty(docTeamFeedbackTypeEntityList)) {
                    for (DocTeamFeedbackType docTeamFeedbackTypeEntity : docTeamFeedbackTypeEntityList) {
                        docTeamFeedbackTypeEntity.setMedicalTeamId(docTeamEntity.getMedicalTeamId());
                        docTeamFeedbackTypeDAO.save(docTeamFeedbackTypeEntity);
                    }
                }
            }
            return docTeamEntity;
            //return BaseRespUtil.setResultSuccess(docTeamEntity);
        } else {//修改
            docTeamEntity = docTeamDAO.get(addDocTeamReq.getMedicalTeamId());
            if (null == docTeamEntity) {
                throw new ControllerException("该团队不存在，修改失败");
            }
            BeanUtils.copyProperties(addDocTeamReq, docTeamEntity);
            docTeamEntity.setGmtModified(new Date());
            docTeamDAO.update(docTeamEntity);

            if ("1".equals(addDocTeamReq.getTeamType())) {
                List<DocTeamDiseaseEntity> docTeamDiseaseEntityList = addDocTeamReq.getTeamChronicDiseaseList();
                if (CollectionUtils.isNotEmpty(docTeamDiseaseEntityList)) {
                    //先删除慢病列表
                    docTeamDiseaseRpcService.deleteDiseaseByTeamId(addDocTeamReq.getMedicalTeamId());
                    //再新增
                    for (DocTeamDiseaseEntity teamDiseaseEntity : docTeamDiseaseEntityList) {
                        //选中的科室代码和上级科室代码相同，说明选中的是一级科室，保存的时候上级科室代码设为空
                        if (teamDiseaseEntity.getDepartmentId().equals(teamDiseaseEntity.getSuperiorDepartmentId())) {
                            teamDiseaseEntity.setSuperiorDepartmentId(null);
                            teamDiseaseEntity.setSuperiorDepartmentName(null);
                        }
                        teamDiseaseEntity.setMedicalTeamId(addDocTeamReq.getMedicalTeamId());
                        teamDiseaseEntity.setGmtCreate(new Date());
                        docTeamDiseaseRpcService.save(teamDiseaseEntity);
                    }
                }
            } else if ("4".equals(addDocTeamReq.getTeamType()) || "3".equals(addDocTeamReq.getTeamType())) {
                List<DocTeamFusAuthority> docTeamFusList = addDocTeamReq.getTeamFusAuthorityList();
                if (CollectionUtils.isNotEmpty(docTeamFusList)) {
                    docTeamFusAuthorityService.deleteFusByTeamId(addDocTeamReq.getMedicalTeamId());
                    //再新增
                    for (DocTeamFusAuthority docTeamFusAuthority : docTeamFusList) {
                        //选中的科室代码和上级科室代码相同，说明选中的是一级科室，保存的时候上级科室代码设为空
                        String departmentId = docTeamFusAuthority.getDepartmentId();
                        if (!StringUtils.isEmpty(departmentId) && departmentId.equals(docTeamFusAuthority.getSuperiorDepartmentId())) {
                            docTeamFusAuthority.setSuperiorDepartmentId(null);
                            docTeamFusAuthority.setSuperiorDepartmentName(null);
                        }
                        docTeamFusAuthority.setMedicalTeamId(addDocTeamReq.getMedicalTeamId());
                        docTeamFusAuthorityService.save(docTeamFusAuthority);
                    }
                }


            }
            //意见反馈团队
            else if ("2".equals(addDocTeamReq.getTeamType())) {
                List<DocTeamSurveyQuestionnaireEntity> docTeamSurveyQuestionnaireEntityList = addDocTeamReq.getTeamSurveyQuestionnaireList();
                docTeamSurveyQuestionnaireRpcService.deleteSurveyQuestionnaireByTeamId(addDocTeamReq.getMedicalTeamId());
                if (CollectionUtils.isNotEmpty(docTeamSurveyQuestionnaireEntityList)) {
                    for (DocTeamSurveyQuestionnaireEntity docTeamSurveyQuestionnaireEntity : docTeamSurveyQuestionnaireEntityList) {
                        docTeamSurveyQuestionnaireEntity.setMedicalTeamId(docTeamEntity.getMedicalTeamId());
                        docTeamSurveyQuestionnaireRpcService.save(docTeamSurveyQuestionnaireEntity);
                    }
                }
                List<DocTeamFeedbackType> docTeamFeedbackTypeEntityList = addDocTeamReq.getDocTeamFeedbackTypeList();
                docTeamFeedbackTypeDAO.deleteTeamFeedbackTypeByTeamId(addDocTeamReq.getMedicalTeamId());
                if (CollectionUtils.isNotEmpty(docTeamFeedbackTypeEntityList)) {
                    for (DocTeamFeedbackType docTeamFeedbackTypeEntity : docTeamFeedbackTypeEntityList) {
                        docTeamFeedbackTypeEntity.setMedicalTeamId(docTeamEntity.getMedicalTeamId());
                        docTeamFeedbackTypeDAO.save(docTeamFeedbackTypeEntity);
                    }
                }
            }
            return docTeamEntity;
        }
    }


    /**
     * @description: 保存团队疾病列表
     * @author: chenJij@bsoft.com.cn
     * @date: 2020/8/24 20:57
     */
    @Override
    @RpcService
    public void addTeamChronicDiseaseList(AddTeamChronicDiseaseListReq addTeamChronicDiseaseListReq) throws ControllerException {
        List<DocTeamDiseaseEntity> docTeamDiseaseEntityList = addTeamChronicDiseaseListReq.getTeamChronicDiseaseList();
        if (addTeamChronicDiseaseListReq.getMedicalTeamId() == null) {//新增 无团队添加病种 放在缓存里

            String teamChronicDiseaseListString =
                    redisUtil.get("teamChronicDiseaseList:" + addTeamChronicDiseaseListReq.getChronicDiseaseIndex());
            if (CommonUtils.isNotEmpty(teamChronicDiseaseListString)) {
                List<DocTeamDiseaseEntity> teamDiseaseEntityList = JSONArray.parseArray(teamChronicDiseaseListString,
                        DocTeamDiseaseEntity.class);
                docTeamDiseaseEntityList.addAll(teamDiseaseEntityList);
            }

            if (CollectionUtils.isNotEmpty(docTeamDiseaseEntityList)) {
                redisUtil.set("teamChronicDiseaseList:" + addTeamChronicDiseaseListReq.getChronicDiseaseIndex(),
                        JSONUtils.writeValueAsString(docTeamDiseaseEntityList), 24 * 3600);
            }

            return;
        } else {//修改  有团队追加病种
            if (CollectionUtils.isNotEmpty(docTeamDiseaseEntityList)) {
                List<DocTeamDiseaseEntity> tempDocTeamDisease =
                        docTeamDiseaseRpcService.queryDocTeamDiseaseList(addTeamChronicDiseaseListReq.getMedicalTeamId());
                //判断是否重复添加同一病种
                if (CollectionUtils.isNotEmpty(tempDocTeamDisease)) {
                    HashSet<String> idSet = new HashSet<>();
                    for (DocTeamDiseaseEntity docTeamDiseaseEntity :
                            tempDocTeamDisease) {
                        idSet.add(docTeamDiseaseEntity.getChronicDiseaseId());
                    }
                    int i = 0;
                    for (DocTeamDiseaseEntity docTeamDiseaseEntity :
                            docTeamDiseaseEntityList) {
                        if (CommonUtils.isNull(docTeamDiseaseEntity.getTeamChronicDiseaseId())) {
                            idSet.add(docTeamDiseaseEntity.getChronicDiseaseId());
                        } else {
                            i++;
                        }
                    }
                    if (idSet.size() < (docTeamDiseaseEntityList.size() + tempDocTeamDisease.size() - i)) {
                        throw new ControllerException("团队管辖病种存在重复");
                    }
                }
                //新增
                for (DocTeamDiseaseEntity teamDiseaseEntity : docTeamDiseaseEntityList) {
                    //选中的科室代码和上级科室代码相同，说明选中的是一级科室，保存的时候上级科室代码设为空
                    if (teamDiseaseEntity.getDepartmentId().equals(teamDiseaseEntity.getSuperiorDepartmentId())) {
                        teamDiseaseEntity.setSuperiorDepartmentId(null);
                        teamDiseaseEntity.setSuperiorDepartmentName(null);
                    }
                    teamDiseaseEntity.setMedicalTeamId(addTeamChronicDiseaseListReq.getMedicalTeamId());
                    teamDiseaseEntity.setGmtCreate(new Date());
                    long teamChronicDiseaseId = teamDiseaseEntity.getTeamChronicDiseaseId();
                    if (teamChronicDiseaseId != 0) {
                        continue;
                    }
                    docTeamDiseaseRpcService.save(teamDiseaseEntity);
                }
            }

            return;
        }
    }

    /**
     * @description: 没有团队id，从redis缓存查询团队疾病列表，用于团队未保存时的初始化疾病列表;有团队id，直接返回团队病种列表
     * @date: 2020/8/24 20:17
     */
    @Override
    @RpcService
    public List<DocTeamDiseaseEntity> queryTeamChronicDiseaseList(QueryTeamChronicDiseaseListReq queryTeamChronicDiseaseListReq) throws ControllerException {
        List<DocTeamDiseaseEntity> docTeamDiseaseEntityList = null;
        //团队id不存在
        if (null == queryTeamChronicDiseaseListReq.getMedicalTeamId()) {
            String teamChronicDiseaseListString = redisUtil.get("teamChronicDiseaseList:" + queryTeamChronicDiseaseListReq.getChronicDiseaseIndex());
            if (CommonUtils.isNotEmpty(teamChronicDiseaseListString)) {
                docTeamDiseaseEntityList = JSONArray.parseArray(teamChronicDiseaseListString, DocTeamDiseaseEntity.class);
            }
        } else {//团队id存在
            docTeamDiseaseEntityList = docTeamDiseaseRpcService.queryDocTeamDiseaseList(queryTeamChronicDiseaseListReq.getMedicalTeamId());
        }
        if (CommonUtils.isNotEmpty(docTeamDiseaseEntityList)) {
            for (DocTeamDiseaseEntity docTeamDiseaseEntity : docTeamDiseaseEntityList) {
                //上级科室代码为空
                if (CommonUtils.isEmpty(docTeamDiseaseEntity.getSuperiorDepartmentId())) {
                    docTeamDiseaseEntity.setSuperiorDepartmentId(docTeamDiseaseEntity.getDepartmentId());
                    docTeamDiseaseEntity.setSuperiorDepartmentName(docTeamDiseaseEntity.getDepartmentName());
                } else {
                    docTeamDiseaseEntity.setChildDepartmentId(docTeamDiseaseEntity.getDepartmentId());
                    docTeamDiseaseEntity.setChildDepartmentName(docTeamDiseaseEntity.getDepartmentName());
                }
            }
        }
        return docTeamDiseaseEntityList;
    }

    /**
     * @description: 没有团队id，从redis缓存查询团队疾病列表，用于团队未保存时的初始化疾病列表;有团队id，直接删除
     * @date: 2020/8/24 20:17
     */
    @Override
    @RpcService
    public void delTeamChronicDiseaseList(QueryTeamChronicDiseaseListReq queryTeamChronicDiseaseListReq) throws ControllerException {
        //若是团队id为空，从redis缓存删除列表数据
        if (null == queryTeamChronicDiseaseListReq.getMedicalTeamId()) {
            List<String> chronicDiseaseIdList = queryTeamChronicDiseaseListReq.getChronicDiseaseIdList();
            //若是删除的团队疾病id不为空
            if (CommonUtils.isNotEmpty(chronicDiseaseIdList)) {
                String teamChronicDiseaseListString = redisUtil.get("teamChronicDiseaseList:" + queryTeamChronicDiseaseListReq.getChronicDiseaseIndex());
                logger.info("teamChronicDiseaseListString=" + teamChronicDiseaseListString);
                if (CommonUtils.isNotEmpty(teamChronicDiseaseListString)) {
                    List<DocTeamDiseaseEntity> diseaseEntities = new ArrayList<>();
                    //从redis里面取出之前保存的团队疾病列表
                    List<DocTeamDiseaseEntity> docTeamDiseaseEntityList = JSONArray.parseArray(teamChronicDiseaseListString, DocTeamDiseaseEntity.class);
                    if (CommonUtils.isNotEmpty(docTeamDiseaseEntityList)) {
                        for (DocTeamDiseaseEntity docTeamDiseaseEntity : docTeamDiseaseEntityList) {
                            //排除删除的疾病id，把返回结果放入到返回的的疾病列表里
                            if (!chronicDiseaseIdList.contains(docTeamDiseaseEntity.getChronicDiseaseId())) {
                                diseaseEntities.add(docTeamDiseaseEntity);
                            }
                        }
                        String a = JSONUtils.writeValueAsString(diseaseEntities);
                        redisUtil.set("teamChronicDiseaseList:" + queryTeamChronicDiseaseListReq.getChronicDiseaseIndex(), JSONUtils.writeValueAsString(diseaseEntities), 24 * 3600);
                        return;
                    }
                }
            }
        } else {
            //删除慢病列表
            docTeamDiseaseRpcService.deleteDiseaseByChronicDiseaseIdList(queryTeamChronicDiseaseListReq.getMedicalTeamId(), queryTeamChronicDiseaseListReq.getChronicDiseaseIdList());
        }
        return;
    }

    @Override
    @RpcService
    public void delDocTeam(QueryDocTeamListReq docTeamListReq) throws ControllerException {
        DocTeamEntity docTeamEntity = docTeamDAO.get(docTeamListReq.getMedicalTeamId());
        if (null == docTeamEntity) {
            throw new ControllerException("该团队不存在，修改失败");
        }
        Long count = fusTeamChronicGroupRecordService.queryJoinedGroupCount(docTeamListReq.getMedicalTeamId(), null);
        if (count > 0) {
            throw new ControllerException("该团队已有入组患者，不能删除");
        }
        docTeamEntity.setEnableFlag((byte) 3);
        docTeamEntity.setGmtModified(new Date());
        docTeamDAO.update(docTeamEntity);
        return;
    }

    @Override
    @RpcService
    public void addDocTeamMembers(AddDocTeamMemberReq addDocTeamReq) throws ControllerException {
        DocTeamEntity docTeamEntity = docTeamDAO.get(addDocTeamReq.getMedicalTeamId());
        if (null == docTeamEntity || docTeamEntity.getEnableFlag() != 1) {
            throw new ControllerException("团队不存在或已被停用，删除");
        }
        List<DocTeamMemberEntity> teamMemberEntityList = addDocTeamReq.getMedicalTeamMemberList();
        for (DocTeamMemberEntity teamMemberEntity : teamMemberEntityList) {
            Integer count = docTeamMemberDAO.getCountByDoctorId(teamMemberEntity.getDocId(), addDocTeamReq.getMedicalTeamId());
            if (count == null) {
                teamMemberEntity.setMedicalTeamId(addDocTeamReq.getMedicalTeamId());
                teamMemberEntity.setRoleId((byte) 3);
                teamMemberEntity.setRoleName("成员");
                teamMemberEntity.setGmtCreate(new Date());
                docTeamMemberDAO.save(teamMemberEntity);
            }
        }
        return;
    }

    @Override
    @RpcService
    public void delDocTeamMember(QueryDocTeamListReq docTeamListReq) throws ControllerException {
        DocTeamMemberEntity teamMemberEntity = docTeamMemberDAO.get(docTeamListReq.getMedicalTeamMemberId());
        if (teamMemberEntity != null) {
            if (teamMemberEntity.getRoleId() == 1) {//组长
                throw new ControllerException("不能移除团队组长");
            }
            Long count = fusTeamChronicGroupRecordService.queryJoinedGroupCount(docTeamListReq.getMedicalTeamId(), teamMemberEntity.getDoctorId());
            if (count > 0) {
                throw new ControllerException("该医生在该团队已有入组患者，不能删除");
            }
            docTeamMemberDAO.remove(docTeamListReq.getMedicalTeamMemberId());
        } else {
            throw new ControllerException("成员不存在");
        }
        return;
    }

    @Override
    @RpcService
    public String setDocTeamMemberRole(SetMemberRoleReq setMemberRoleReq) throws ControllerException {
        DocTeamMemberEntity teamMemberEntity = docTeamMemberDAO.get(setMemberRoleReq.getMedicalTeamMemberId());
        if (teamMemberEntity == null) {
            throw new ControllerException("成员不存在");
        }
        BeanUtils.copyProperties(setMemberRoleReq, teamMemberEntity);
        teamMemberEntity.setGmtModified(new Date());
        docTeamMemberDAO.update(teamMemberEntity);
        if (setMemberRoleReq.getRoleId() == 1) {//设置的是队长，检查是否已经存在队长
            DocTeamMemberEntity oldCaptain = docTeamMemberDAO.getOldCaptain(setMemberRoleReq.getMedicalTeamId(), setMemberRoleReq.getMedicalTeamMemberId());
            if (oldCaptain != null) {
                oldCaptain.setRoleId((byte) 3);
                oldCaptain.setRoleName("成员");
                teamMemberEntity.setGmtModified(new Date());
                docTeamMemberDAO.update(oldCaptain);
                return "已将" + teamMemberEntity.getDoctorName() + "医生设为队长，并将原队长" + oldCaptain.getDoctorName() + "设为普通成员";
            }
        }
        return "设置成功";
    }

    @RpcService
    public String setDocTeamMemberRoleTest(SetMemberRoleReq setMemberRoleReq) throws ControllerException {
        DocTeamMemberEntity teamMemberEntity = docTeamMemberDAO.get(setMemberRoleReq.getMedicalTeamMemberId());
        if (teamMemberEntity == null) {
            throw new ControllerException("成员不存在");
        }
        BeanUtils.copyProperties(setMemberRoleReq, teamMemberEntity);
        teamMemberEntity.setGmtModified(new Date());
        docTeamMemberDAO.update(teamMemberEntity);
        if (setMemberRoleReq.getRoleId() == 1) {//设置的是队长，检查是否已经存在队长
            DocTeamMemberEntity oldCaptain = docTeamMemberDAO.getOldCaptain(setMemberRoleReq.getMedicalTeamId(), setMemberRoleReq.getMedicalTeamMemberId());
            if (oldCaptain != null) {
                oldCaptain.setRoleId((byte) 3);
                oldCaptain.setRoleName("成员");
                teamMemberEntity.setGmtModified(new Date());
                docTeamMemberDAO.update(oldCaptain);
                return "已将" + teamMemberEntity.getDoctorName() + "医生设为队长，并将原队长" + oldCaptain.getDoctorName() + "设为普通成员";
            }
        }
        return "设置成功";
    }


    @Override
    @RpcService
    public List<DocTeamDiseaseEntity> queryChronicDiseaseList(QueryDocTeamListReq docTeamListReq) throws ControllerException {
        List<DiseaseSpecies> chronicDiseaseList = diseaseSpeciesRpcService.queryDiseaseSpeciesListByOrdAndDept(docTeamListReq);
        List<DocTeamDiseaseEntity> docTeamDiseaseEntityList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(chronicDiseaseList)) {
            //查询团队所拥有的疾病id
            List<String> chronicDiseaseIdList = new ArrayList<>();
            if (null != docTeamListReq.getMedicalTeamId()) {
                List<DocTeamDiseaseEntity> docTeamDiseaseEntities = docTeamDiseaseRpcService.queryDocTeamDiseaseList(docTeamListReq.getMedicalTeamId());
                if (CommonUtils.isNotEmpty(docTeamDiseaseEntities)) {
                    for (DocTeamDiseaseEntity docTeamDiseaseEntity : docTeamDiseaseEntities) {
                        chronicDiseaseIdList.add(docTeamDiseaseEntity.getChronicDiseaseId());
                    }
                }
            }

            //查询缓存里面的疾病列表
            if (CommonUtils.isNotEmpty(docTeamListReq.getChronicDiseaseIndex())) {
                String teamChronicDiseaseListString = redisUtil.get("teamChronicDiseaseList:" + docTeamListReq.getChronicDiseaseIndex());
                if (CommonUtils.isNotEmpty(teamChronicDiseaseListString)) {
                    //从redis里面取出之前保存的团队疾病列表
                    List<DocTeamDiseaseEntity> diseaseEntityList = JSONArray.parseArray(teamChronicDiseaseListString, DocTeamDiseaseEntity.class);
                    if (CommonUtils.isNotEmpty(diseaseEntityList)) {
                        for (DocTeamDiseaseEntity docTeamDiseaseEntity : diseaseEntityList) {
                            chronicDiseaseIdList.add(docTeamDiseaseEntity.getChronicDiseaseId());
                        }
                    }
                }
            }

            for (DiseaseSpecies diseaseSpecies : chronicDiseaseList) {
                DocTeamDiseaseEntity diseaseEntity = new DocTeamDiseaseEntity();
                BeanUtils.copyProperties(diseaseSpecies, diseaseEntity);
                diseaseEntity.setChronicDiseaseId(diseaseSpecies.getDiseaseTypeId() + "");
                diseaseEntity.setChronicDiseaseName(diseaseSpecies.getDiseaseTypeName());
                //过滤，排除团队已有的疾病id
                if (!chronicDiseaseIdList.contains(String.valueOf(diseaseSpecies.getDiseaseTypeId()))) {
                    docTeamDiseaseEntityList.add(diseaseEntity);
                }
            }
        }
        return docTeamDiseaseEntityList;
    }

    @Override
    @RpcService
    public QuerySurveyRuleQuestionListVO querySurveyRuleByDoctorId(QuerySurveyRuleListRequest req) throws ControllerException {


        List<Long> teamIdList = null;
        if(CommonUtils.isNotEmpty(req.getDocId()) && CommonUtils.isNotEmpty(req.getDoctorId())){
            teamIdList = docTeamMemberDAO.findMedicalTeamIdsByDoctorIdAndDocId(req.getDocId(), req.getDoctorId());
        }else if(CommonUtils.isNotEmpty(req.getDocId())){
            teamIdList = docTeamMemberDAO.findMedicalTeamIdsByDoctorId(req.getDocId());
        }else if(CommonUtils.isNotEmpty(req.getDoctorId())){
            teamIdList = docTeamMemberDAO.findMedicalTeamIdList(req.getDoctorId());
        }
        req.setTeamIdList(teamIdList);
        // 4.0.02 根据所在团队id查询有权限的子路径
        List<Long> routeDetailIds = followUpRouteDetailTeamService.queryFollowUpRouteDetailTeamByTeamIdList(teamIdList)
                .stream().map(FollowUpRouteDetailTeam::getRouteDetailId).collect(Collectors.toList());
        req.setRouteDetailIdList(routeDetailIds);

        //查询医生所具备的权限问卷列表
        List<QuerySurveyRuleQuestionListResponse> satisfactionSurveyRulePlans = patientSatisfactionSurveyService.querySurveyRuleByDoctorId(req);

        QuerySurveyRuleQuestionListVO vo = new QuerySurveyRuleQuestionListVO();
        if (CollectionUtils.isNotEmpty(satisfactionSurveyRulePlans)) {
            List<QuerySurveyRuleQuestionListResponse> qList = satisfactionSurveyRulePlans.stream()
                    .filter(q -> ItemTypeEnum.FORM.getType().equals(q.getItemType()))
                    .collect(Collectors.toMap(QuerySurveyRuleQuestionListResponse::getQuestionnaireId, r -> r, (v1, v2) -> v1))
                    .entrySet().stream().map(Map.Entry::getValue).collect(Collectors.toList());
            List<QuerySurveyRuleQuestionListResponse> eList = satisfactionSurveyRulePlans.stream()
                    .filter(q -> ItemTypeEnum.EDUCATION.getType().equals(q.getItemType()))
                    .collect(Collectors.toMap(QuerySurveyRuleQuestionListResponse::getEducationId, r -> r, (v1, v2) -> v1))
                    .entrySet().stream().map(Map.Entry::getValue).collect(Collectors.toList());
            vo.setQuestionList(qList);
            vo.setEducationList(eList);
        }
        return vo;
    }

    @Override
    public List<DocTeamEntity> queryAllDocTeam(QueryAllDocTeamReq req) {
        return docTeamDAO.queryDocTeam(req);
    }

//  /**
//   *
//   *
//   * @author Qulc - 2022/5/23 18:45
//   * @param docTeamFusAuthority the docTeamFusAuthority
//   */
//    @Override
//    @RpcService
//    public void addTeamFus(DocTeamFusAuthority docTeamFusAuthority) throws ControllerException {
//        /*新增---------添加路径权限*/
//        if (docTeamFusAuthority.getFusAuthorityId() == null) {
//            docTeamFusAuthorityService.save(docTeamFusAuthority);
//        } else {
//            throw new ControllerException("团队已存在，请勿新增");
//        }
//
//    }


    /**
     * 团队列表新增---暂时缓存在同一页面，不添加到数据库里
     *
     * @param addDocTeamFusAuthorityListReq the addDocTeamFusAuthorityListReq
     * @author Qulc - 2022/5/24 20:01
     */
    @Override
    @RpcService
    public void addTeamFusList(AddDocTeamFusAuthorityListReq addDocTeamFusAuthorityListReq) throws ControllerException {
        List<DocTeamFusAuthority> docTeamFusAuthorityList = addDocTeamFusAuthorityListReq.getTeamFusAuthorityList();
        if (CommonUtils.isEmpty(addDocTeamFusAuthorityListReq.getMedicalTeamId())) {//新增 无团队添加病种 放在缓存里
            if (CollectionUtils.isNotEmpty(docTeamFusAuthorityList)) {
                redisUtil.set("teamFusList:" + addDocTeamFusAuthorityListReq.getTeamFusIndex(),
                        JSONUtils.writeValueAsString(docTeamFusAuthorityList), 24 * 3600);
            }
            return;
        } else {//修改  有团队追加路径
            if (CollectionUtils.isNotEmpty(docTeamFusAuthorityList)) {
                List<DocTeamFusAuthority> tempDocTeamFus =
                        docTeamFusAuthorityService.queryTeamFusList(addDocTeamFusAuthorityListReq.getMedicalTeamId());
                //判断是否重复添加同一病种
                if (CollectionUtils.isNotEmpty(tempDocTeamFus)) {
                    HashSet<String> idSet = new HashSet<>();
                    //数据库里的数据
                    for (DocTeamFusAuthority docTeamFusAuthority :
                            tempDocTeamFus) {
                        String organizationId = StringUtils.isEmpty(docTeamFusAuthority.getOrganizationId()) ? "$" : docTeamFusAuthority.getOrganizationId();
                        String departmentId = StringUtils.isEmpty(docTeamFusAuthority.getDepartmentId()) ? "$" : docTeamFusAuthority.getDepartmentId();
                        idSet.add(organizationId + "-" + departmentId + "-"
                                + docTeamFusAuthority.getRouteId());
                    }
                    int i = 0;
                    //前端传的数据
                    for (DocTeamFusAuthority docTeamFusAuthority :
                            docTeamFusAuthorityList) {
                        if (CommonUtils.isNull(docTeamFusAuthority.getFusAuthorityId())) {
                            String organizationId = StringUtils.isEmpty(docTeamFusAuthority.getOrganizationId()) ? "$" : docTeamFusAuthority.getOrganizationId();
                            String departmentId = StringUtils.isEmpty(docTeamFusAuthority.getDepartmentId()) ? "$" : docTeamFusAuthority.getDepartmentId();
                            idSet.add(organizationId + "" + departmentId + "-" + docTeamFusAuthority.getRouteId());
                        } else {
                            i++;
                        }
                    }
                    if (idSet.size() < (docTeamFusAuthorityList.size() + tempDocTeamFus.size() - i)) {
                        throw new ControllerException("团队管辖路径存在重复");
                    }
                }
                //新增
                for (DocTeamFusAuthority teamFusAuthorityEntity : docTeamFusAuthorityList) {
                    //选中的科室代码和上级科室代码相同，说明选中的是一级科室，保存的时候上级科室代码设为空
                    if (!StringUtils.isEmpty(teamFusAuthorityEntity.getDepartmentId()) &&
                            !StringUtils.isEmpty(teamFusAuthorityEntity.getSuperiorDepartmentId()) &&
                            teamFusAuthorityEntity.getDepartmentId().equals(teamFusAuthorityEntity.getSuperiorDepartmentId())) {
                        teamFusAuthorityEntity.setSuperiorDepartmentId(null);
                        teamFusAuthorityEntity.setSuperiorDepartmentName(null);
                    }
                    teamFusAuthorityEntity.setMedicalTeamId(addDocTeamFusAuthorityListReq.getMedicalTeamId());
                    Long fusAuthorityId = teamFusAuthorityEntity.getFusAuthorityId();
                    if (Objects.nonNull(fusAuthorityId)) {
                        continue;
                    }
                    docTeamFusAuthorityService.save(teamFusAuthorityEntity);
                }
            }
            return;
        }
    }

    /**
     * 团队列表新增---当前页面查询，不查询数据库，根据当前时间查询
     *
     * @param queryDocTeamFusAuthorityListReq the queryDocTeamFusAuthorityListReq
     * @author Qulc - 2022/5/25 11:27
     */
    @Override
    @RpcService
    public List<DocTeamFusAuthority> queryTeamList(QueryDocTeamFusAuthorityListReq queryDocTeamFusAuthorityListReq) throws ControllerException {
        List<DocTeamFusAuthority> docTeamFusAuthorityList = null;
        //团队id不存在
        if (CommonUtils.isEmpty(queryDocTeamFusAuthorityListReq.getMedicalTeamId())) {
            String teamFusListString = redisUtil.get("teamFusList:" + queryDocTeamFusAuthorityListReq.getTeamFusIndex());
            if (CommonUtils.isNotEmpty(teamFusListString)) {
                docTeamFusAuthorityList = JSONArray.parseArray(teamFusListString, DocTeamFusAuthority.class);
            }
        } else {//团队id存在
            docTeamFusAuthorityList = docTeamFusAuthorityService.queryDocTeamFusList(queryDocTeamFusAuthorityListReq.getMedicalTeamId());
        }
        if (CommonUtils.isNotEmpty(docTeamFusAuthorityList)) {
            for (DocTeamFusAuthority docTeamFusEntity : docTeamFusAuthorityList) {
                //上级科室代码为空
                if (CommonUtils.isEmpty(docTeamFusEntity.getSuperiorDepartmentId())) {
                    docTeamFusEntity.setSuperiorDepartmentId(docTeamFusEntity.getDepartmentId());
                    docTeamFusEntity.setSuperiorDepartmentName(docTeamFusEntity.getDepartmentName());
                } else {
                    docTeamFusEntity.setDepartmentId(docTeamFusEntity.getDepartmentId());
                    docTeamFusEntity.setDepartmentName(docTeamFusEntity.getDepartmentName());
                }
            }
        }
        return docTeamFusAuthorityList;
    }


    @Override
    @RpcService
    public void delTeamFusList(DelDocTemFusReq delDocTemFusReq) throws ControllerException {
        //若是团队id为空，从redis缓存删除列表数据
        if (CommonUtils.isEmpty(delDocTemFusReq.getMedicalTeamId())) {
            List<Long> teamFusIdList = delDocTemFusReq.getTeamFusAuthorityList();
            //若是删除的团队路径id不为空
            if (CommonUtils.isNotEmpty(teamFusIdList)) {
                String teamFusListString = redisUtil.get("teamFusList:" + delDocTemFusReq.getTeamFusIndex());
                logger.info("teamFusListString=" + teamFusListString);
                if (CommonUtils.isNotEmpty(teamFusListString)) {
                    List<DocTeamFusAuthority> fusTeamList = new ArrayList<>();
                    //从redis里面取出之前保存的团队路径列表
                    List<DocTeamFusAuthority> docTeamFusEntityList = JSONArray.parseArray(teamFusListString, DocTeamFusAuthority.class);
                    if (CommonUtils.isNotEmpty(docTeamFusEntityList)) {
                        for (DocTeamFusAuthority docTeamFusAuthority : docTeamFusEntityList) {
                            //排除删除的路径id，把返回结果放入到返回的的路径列表里
                            if (!teamFusIdList.contains(docTeamFusAuthority.getRouteId())) {
                                fusTeamList.add(docTeamFusAuthority);
                            }
                        }
                        String a = JSONUtils.writeValueAsString(fusTeamList);
                        redisUtil.set("teamFusList:" + delDocTemFusReq.getTeamFusIndex(), JSONUtils.writeValueAsString(fusTeamList), 24 * 3600);
                        return;
                    }
                }
            }
        } else {
            //删除慢病列表
            docTeamFusAuthorityService.deleteFusTeamList(delDocTemFusReq.getMedicalTeamId(), delDocTemFusReq.getTeamFusAuthorityList());
        }
        return;
    }

    @Override
    @RpcService
    public List<QueryDocTeamListResp> queryByDiseaseTypeId(Long diseaseTypeId) throws ControllerException {

        List<QueryDocTeamListResp> result = Lists.newArrayList();
        if (Objects.isNull(diseaseTypeId)){
            throw new ControllerException("病种id");
        }
        List<Long> teamIdList = docTeamDiseaseRpcService.queryMedicalTeamIdList(String.valueOf(diseaseTypeId));
        if (CollectionUtils.isEmpty(teamIdList)){
            return result;
        }
        QueryDocTeamListReq docTeamListReq = new QueryDocTeamListReq();
        docTeamListReq.setTeamIdList(teamIdList);
        return docTeamDAO.queryDocTeamList(docTeamListReq);
    }

    @Override
    public List<QueryDocTeamListResp> queryByRouteId(Long routeId) throws ControllerException {
        if (Objects.isNull(routeId)){
            throw new ControllerException("随访路径id");
        }
        List<DocTeamFusAuthority> teamFusAuthorityList = docTeamFusAuthorityService.queryDocTeamFusListByRouteId(routeId);
        if(CollectionUtils.isEmpty(teamFusAuthorityList)){
            return Lists.newArrayList();
        }
        QueryDocTeamListReq docTeamListReq = new QueryDocTeamListReq();
        docTeamListReq.setTeamIdList(teamFusAuthorityList.stream().map(DocTeamFusAuthority::getMedicalTeamId)
                .collect(Collectors.toList()));
        return docTeamDAO.queryDocTeamList(docTeamListReq);
    }


    /**
     * 查询该团队拥有的随访路径权限列表(新增)
     *
     * @param addDocTeamFusAuthorityReq the addDocTeamFusAuthorityReq
     * @author Qulc - 2022/5/23 17:31
     */
    @Override
    @RpcService
    public List<DocTeamFusAuthority> queryTeamFusList(AddDocTeamFusAuthorityReq addDocTeamFusAuthorityReq) throws ControllerException {
        List<DocTeamFusAuthority> reqList = new ArrayList<>();
        if (CommonUtils.isNotEmpty(addDocTeamFusAuthorityReq.getMedicalTeamId())) {
            String medicalTeamId = addDocTeamFusAuthorityReq.getMedicalTeamId();
            if(CommonUtils.isNotEmpty(medicalTeamId)){
                reqList = docTeamFusAuthorityService.queryTeamFusList(Long.valueOf(medicalTeamId));
            }
        } else {
            throw new ControllerException("团队id为空，请核对后重新输入");
        }

        return reqList;
    }


}
